package com.cowmooed.exception;

import com.cowmooed.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * 全局异常处理类
 * 用于统一处理系统中的所有异常
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理所有未捕获的Exception
     * @param request 请求对象
     * @param e 异常对象
     * @return 统一的错误响应
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handleException(HttpServletRequest request, Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);
        log.error("请求URL: {}", request.getRequestURL());
        log.error("请求方法: {}", request.getMethod());
        log.error("请求参数: {}", request.getQueryString());
        return Result.error("服务器内部错误，请稍后重试");
    }

    /**
     * 处理数据库相关异常
     * @param request 请求对象
     * @param e SQLException异常
     * @return 统一的错误响应
     */
    @ExceptionHandler(SQLException.class)
    @ResponseBody
    public Result handleSQLException(HttpServletRequest request, SQLException e) {
        log.error("数据库异常: {}", e.getMessage(), e);
        return Result.error("数据库操作失败，请稍后重试");
    }

    /**
     * 处理404异常
     * @param request 请求对象
     * @param e NoHandlerFoundException异常
     * @return 统一的错误响应
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public Result handleNoHandlerFoundException(HttpServletRequest request, NoHandlerFoundException e) {
        log.error("请求的资源不存在: {}", request.getRequestURL());
        return Result.error("请求的资源不存在");
    }

    /**
     * 处理空指针异常
     * @param request 请求对象
     * @param e NullPointerException异常
     * @return 统一的错误响应
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public Result handleNullPointerException(HttpServletRequest request, NullPointerException e) {
        log.error("空指针异常: {}", e.getMessage(), e);
        log.error("堆栈跟踪: {}", Arrays.toString(e.getStackTrace()));
        return Result.error("系统内部错误，请稍后重试");
    }

    /**
     * 处理自定义业务异常
     * @param request 请求对象
     * @param e 自定义业务异常
     * @return 统一的错误响应
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result handleBusinessException(HttpServletRequest request, BusinessException e) {
        log.error("业务异常: {}", e.getMessage());
        return Result.error(e.getMessage());
    }

    /**
     * 自定义业务异常类
     * 用于抛出业务逻辑相关的异常
     */
    public static class BusinessException extends RuntimeException {
        public BusinessException(String message) {
            super(message);
        }
    }
}